package com.fourWork.workFour;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 输入输出流通信
 */
public class ServerThread extends Thread {
    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //3.使用输入输出流进行通信
        BufferedReader bufferedReader = null;
        PrintStream printStream=null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printStream=new PrintStream(socket.getOutputStream());

            while(true){
                //实现对客户端发来字符串内容的接受并打印
                //当没有数据发来是，下面的方法会形成阻塞
                String s = bufferedReader.readLine();
                //获取客户端IP
                InetAddress inetAddress = socket.getInetAddress();
                System.out.println("客户端"+inetAddress+"发来的字符串内容是："+s);
                //实现服务器向客户端回发字符串内容 服务器接收成功
                System.out.println(s);
                printStream.println(s.contains("admin")&&s.contains("123456")?"success":"fail");
                System.out.println("服务器发送数据成功");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null!=printStream){
                printStream.close();
            }
            if(null!=bufferedReader){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=socket){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
